<?php

namespace App\Http\Controllers;

use App\Base\Handlers\ImageUploadHandler;
use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * 用户信息
 *
 * Class UsersController
 * @package App\Http\Controllers
 */
class UsersController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * 展示用户信息详情
     *
     * @param User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(User $user)
    {
        return view('users.show', compact('user'));
    }

    public function host(User $user)
    {
        return view('users.host', compact('user'));
    }

    /**
     * 编辑用户信息
     *
     * @param User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function edit(User $user)
    {
        $this->authorize('update', $user);
        return view('users.edit', compact('user'));
    }

    /**
     * 更新用户信息操作
     *
     * @param UserRequest $request
     * @param ImageUploadHandler $uploader
     * @param User $user
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(UserRequest $request, ImageUploadHandler $uploader, User $user)
    {
        // 添加用户更新规则
        $this->authorize('update', $user);
        // 获取所有的数据
        $data = $request->all();
        // 处理头像操作
        if ($request->avatar) {
            $result = $uploader->save($request->avatar, 'avatars', $user->id, 362);
            if ($result) {
                $data['avatar'] = $result['path'];
            }
        }
        $user->update($data);
        return redirect()->route('users.show', $user->id)->with('success', '个人资料更新成功！');
    }

    /**
     * 展示用户头像
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function avatar()
    {
        return view('users.avatar');
    }

    /**
     * 修改用户头像
     *
     * @param Request $request
     * @return array
     */
    public function changeAvatar(Request $request, ImageUploadHandler $uploader)
    {
        $file = $request->file('img');
        $result = $uploader->save($file,'avatars', user()->id, 362);
        // print_r($result['path']);
        user()->avatar = $result['path'];
        user()->save();

        // 七牛云 文件上传
//        $filename = 'images/avatar' . md5(time() . user()->id) . '.' . $file->getClientOriginalExtension();
//        Storage::disk('qiniu')->writeStream($filename, fopen($file->getRealPath(), 'r'));
//        user()->avatar = 'http://' . config('filesystems.disks.qiniu.domain') . '/' . $filename;
//        user()->save();
        return ['url' => user()->avatar];
    }
}
